package com.vogue.supplymall.match.domain.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vogue.ssm.database.dao.BaseDao;
import com.vogue.ssm.database.entity.SnowflakeIdWorker;
import com.vogue.ssm.database.util.DealStatus;
import com.vogue.supplymall.account.domain.model.Address;
import com.vogue.supplymall.account.domain.service.BaseCodeService;
import com.vogue.supplymall.common.domain.tool.BeanToolsUtils;
import com.vogue.supplymall.match.domain.dao.MatchOrganDao;
import com.vogue.supplymall.match.domain.dto.BaseDTO;
import com.vogue.supplymall.match.domain.dto.GoodsDetailsDTO;
import com.vogue.supplymall.match.domain.dto.GoodsPropertiesDTO;
import com.vogue.supplymall.match.domain.dto.GoodsPropertiesDetailsDTO;
import com.vogue.supplymall.match.domain.dto.GoodsproPertiesValueDTO;
import com.vogue.supplymall.match.domain.dto.ProductDTO;
import com.vogue.supplymall.match.domain.dto.ProductDataDTO;
import com.vogue.supplymall.match.domain.dto.ProductPriceDTO;
import com.vogue.supplymall.match.domain.dto.ProductPriceDataDTO;
import com.vogue.supplymall.match.domain.dto.ProductPricePertiesValueDTO;
import com.vogue.supplymall.match.domain.dto.ProductPricePropertiesDetailsDTO;
import com.vogue.supplymall.match.domain.dto.SellerOrganDTO;
import com.vogue.supplymall.match.domain.dto.ImgDTO;
import com.vogue.supplymall.match.domain.dto.ProductCustomerDataDTO;
import com.vogue.supplymall.match.domain.dto.ProductCustomerDetailsDTO;
import com.vogue.supplymall.match.domain.dto.ProductCustomerGoodsDTO;
import com.vogue.supplymall.match.domain.dto.StoreDTO;
import com.vogue.supplymall.match.domain.model.MatchOrgan;
import com.vogue.supplymall.match.domain.model.RelUserOrgan;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.match.domain.service.MatchProductService;
import com.vogue.supplymall.shop.domain.model.OrganShopImg;
import com.vogue.supplymall.shop.domain.model.Product;
import com.vogue.supplymall.shop.domain.model.ProductAttrplan;
import com.vogue.supplymall.shop.domain.model.ProductAttrplanDetail;
import com.vogue.supplymall.shop.domain.model.ProductAttrvalue;
import com.vogue.supplymall.shop.domain.model.ProductDetails;
import com.vogue.supplymall.shop.domain.model.ProductImg;
import com.vogue.supplymall.shop.domain.model.ProductPrice;
import com.vogue.supplymall.shop.domain.model.RelProductCategory;
import com.vogue.supplymall.shop.domain.model.RelProductCode;
import com.vogue.supplymall.shop.domain.model.Shop;
import com.vogue.supplymall.shop.domain.service.ProductAttrplanDetailService;
import com.vogue.supplymall.shop.domain.service.ProductAttrplanService;
import com.vogue.supplymall.shop.domain.service.ProductAttrvalueService;
import com.vogue.supplymall.shop.domain.service.ProductDetailsService;
import com.vogue.supplymall.shop.domain.service.ProductImgService;
import com.vogue.supplymall.shop.domain.service.ProductPriceService;
import com.vogue.supplymall.shop.domain.service.ProductService;
import com.vogue.supplymall.shop.domain.service.RelProductCategoryService;
import com.vogue.supplymall.shop.domain.service.RelProductCodeService;
import com.vogue.supplymall.shop.domain.service.ShopService;

@Service("matchProductService")
@Transactional
public class MatchProductServiceImpl extends BaseServiceImpl<MatchOrgan, Long> implements MatchProductService{
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductDetailsService productDetailsService;
	@Autowired
	private ProductImgService productImgService;
	@Autowired
	private ProductAttrvalueService productAttrvalueService;
	@Autowired
	private ProductAttrplanService productAttrplanService;
	@Autowired
	private ProductPriceService productPriceService;
	@Autowired
	private ProductAttrplanDetailService productAttrplanDetailService;
	@Resource
	private BaseCodeService baseCodeService;
	@Autowired
	private ShopService shopService;
	@Autowired
	private ProductAttrvalueService productAttrValueService;
	@Autowired
	private RelProductCategoryService relProductCategoryService;
	@Autowired
	private MatchOrganService matchOrganService;
	@Autowired
	private RelProductCodeService relProductCodeService;
	
	public MatchProductServiceImpl(BaseDao<MatchOrgan, Long> baseDao) {
		super(baseDao);
	}

	public static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public Map<String, Object> matchProductInfo(BaseDTO<List<ProductDataDTO>> baseDTO) throws Exception {
		if (baseDTO!=null&&baseDTO.getData()!=null) {
			Long sysCodeId =baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
			String updateIds="";
			String organMatchId="";
			Long shopId=0L;
			
			List<ProductDataDTO> productDataDTOs=baseDTO.getData();
			for(ProductDataDTO pdDTO:productDataDTOs) {
				organMatchId=pdDTO.getShopId();
				//先找到对应的match_organ 中的id
				Long organId=matchOrganService.getMatchOrganIdBySM(sysCodeId, organMatchId);
				//再找到对应的shopId
				Shop shop=shopService.getShop(sysCodeId, organId);
				shopId=shop.getId();
				List<ProductDTO> productDTOs=pdDTO.getDetails();
				
				//给商品和单位的oper（新增或更新）列赋值
				productDTOs=this.checkProductOper(shopId, sysCodeId, productDTOs);
				
				for(ProductDTO productDTO:productDTOs) {
					Product	product=null;
				    product=saveProduct(product,productDTO, sysCodeId,shopId);
			
				    if(productDTO.getOper()==1) {
				    	updateIds+=product.getId()+",";
				    	
				    }
				}
				
				//判断门店下的商品是否全部隐藏，如果全部隐藏，则门店隐藏，否则门店不隐藏。
				this.changeShopHiddenFlag(sysCodeId, shop);
				
			}
			
			//当有商品更新时，更改商品禁用标记，新增商品不允许直接下架,所以不需要做判断
			//同时还要判断商品是否有且只有一个默认单位，如果没有，则将系统默认设置最先上传的单位为默认单位，
			//如果有多个默认单位，系统将更新时间最新的单位设置为默认单位
			if(StringUtils.isNotBlank(updateIds)) {
				this.checkProductDisabledFlag(sysCodeId, updateIds);
				this.checkProductDefaultUnit(sysCodeId, updateIds);
			}
		}
		return null;
	}
	
	/**
	 * 判断商品是否是新增，并重新整理数据结构
	 */
	public List<ProductDTO> checkProductOper(Long shopId,Long syscodeId,List<ProductDTO> productDTOs) throws Exception{
		List<ProductDTO> pDTOList=new ArrayList<>();
		final int ZERO=0;
		final int ONE=1;
		
		//得到现有的所有商品和商品单位
		List<Map<String, Object>> pList=productService.getProductInfoBySS(syscodeId, shopId);
		
		if(pList.size()==0||pList.get(0)==null) {	//说明是第一次上传商品，都是新增状态
			for(ProductDTO productDTO:productDTOs) {
				 ProductDTO newPDTO=this.setValueForOper(productDTO,ZERO,ZERO);
				
				pDTOList.add(newPDTO);
			}
			
		}else {
			for(ProductDTO productDTO:productDTOs) {
				boolean existFlag=false;
				boolean whileFlag=true;
				List<String> unitList=new ArrayList<>();
				
				String matchId=productDTO.getMatchid();
				
				//判断商品是否在商城已存在
				for(Map<String, Object> map:pList) {
					if(matchId.equals(((String) map.get("matchid")))) {
						unitList.add((String) map.get("unit_matchid"));
						existFlag=true;
						whileFlag=true;
					}else {
						whileFlag=false;
					}
					
					if((!whileFlag)&&unitList.size()>0) {
						break;
					}
					
				}
				
				//给商品信息的操作列oper赋值
				if(existFlag) {				//商品存在，判断单位是否存在
					
					ProductDTO newPDTO=new ProductDTO();
					BeanUtils.copyProperties(newPDTO, productDTO);
					
					//给商品属性oper列赋值
					List<GoodsPropertiesDTO> newGpDTOs=new ArrayList<>();
					List<GoodsPropertiesDTO> gpDTOs=productDTO.getGoodsproperties();
					
					//给与商品属性组合对应的值的oper列赋值，此oper列的值和商品属性的oper列值必须一致
					List<GoodsproPertiesValueDTO> newgpvDTOs=new ArrayList<>();
					List<GoodsproPertiesValueDTO> gpvDTOs=productDTO.getGoodspropertiesvalue();
					
					for(GoodsPropertiesDTO gpDTO:gpDTOs) {
						List<GoodsPropertiesDetailsDTO> newGpdDTOs=new ArrayList<>();
						List<GoodsPropertiesDetailsDTO> gpdDTOs=gpDTO.getDetails();
						
						for(GoodsPropertiesDetailsDTO gpdDTO:gpdDTOs) {
							GoodsPropertiesDetailsDTO newGpdDTO=new GoodsPropertiesDetailsDTO();
							BeanUtils.copyProperties(newGpdDTO, gpdDTO);
							
							String pertiesid=gpdDTO.getPertiesid();
							if(unitList.contains(pertiesid)) {			//单位存在
								
								//组装商品属性详细值
								newGpdDTO.setOper(ONE);	
								
								//给与商品属性组合对应的值的oper列赋值
								for(GoodsproPertiesValueDTO gpvDTO:gpvDTOs) {
									GoodsproPertiesValueDTO newGpDTO=new GoodsproPertiesValueDTO();
									BeanUtils.copyProperties(newGpDTO, gpvDTO);
									
									String ids=gpvDTO.getIds();
									if(pertiesid.equals(ids)) {
										//组装商品属性组合对应的值
										newGpDTO.setOper(ONE);
										newgpvDTOs.add(newGpDTO);
										break;
									}
									
								}
								
							}else {										//单位不存在
								//组装商品属性详细值
								newGpdDTO.setOper(ZERO);
								
								//给与商品属性组合对应的值的oper列赋值
								for(GoodsproPertiesValueDTO gpvDTO:gpvDTOs) {
									GoodsproPertiesValueDTO newGpDTO=new GoodsproPertiesValueDTO();
									BeanUtils.copyProperties(newGpDTO, gpvDTO);
									
									String ids=gpvDTO.getIds();
									if(pertiesid.equals(ids)) {
										//组装商品属性组合对应的值
										newGpDTO.setOper(ZERO);
										newgpvDTOs.add(newGpDTO);
										break;
									}
									
								}
								
							}
							
							//组装商品属性值
							newGpdDTOs.add(newGpdDTO);
						}
						
						gpDTO.setDetails(newGpdDTOs);
						newGpDTOs.add(gpDTO);
					}
					
					newPDTO.setOper(ONE);
					newPDTO.setGoodsproperties(newGpDTOs);
					newPDTO.setGoodspropertiesvalue(newgpvDTOs);
					pDTOList.add(newPDTO);
					
				}else {						//商品不存在，单位也肯定不存在,oper列值赋0
					
					ProductDTO newPDTO=this.setValueForOper(productDTO,ZERO,ZERO);			
					pDTOList.add(newPDTO);
				}
			}
		}
		
		return pDTOList;
	}
	
	//商品再商城不存在，将oper列值赋为0
	public ProductDTO setValueForOper(ProductDTO productDTO,int productOper,int unitOper) throws Exception{
		boolean defaultUnitFlag=false;
		int cnt=0;
		int defaultCnt=0;
		ProductDTO newPDTO=new ProductDTO();
		BeanUtils.copyProperties(newPDTO, productDTO);
		
		//给商品属性oper列赋值
		List<GoodsPropertiesDTO> newGpDTOs=new ArrayList<>();
		List<GoodsPropertiesDTO> gpDTOs=productDTO.getGoodsproperties();
		for(GoodsPropertiesDTO gpDTO:gpDTOs) {
			List<GoodsPropertiesDetailsDTO> newGpdDTOs=new ArrayList<>();
			List<GoodsPropertiesDetailsDTO> gpdDTOs=gpDTO.getDetails();
			
			for(GoodsPropertiesDetailsDTO gpdDTO:gpdDTOs) {
				GoodsPropertiesDetailsDTO newGpdDTO=new GoodsPropertiesDetailsDTO();
				BeanUtils.copyProperties(newGpdDTO, gpdDTO);
				
				newGpdDTO.setOper(unitOper);
				newGpdDTOs.add(newGpdDTO);
			}
			
			gpDTO.setDetails(newGpdDTOs);
			newGpDTOs.add(gpDTO);
		}
		
		
		//给与商品属性组合对应的值的oper列赋值，此oper列的值和商品属性的oper列值必须一致
		//判断是否有默认单位，没有默认单位，系统自动默认，默认单位多了，系统自动去掉多余的默认单位
		List<GoodsproPertiesValueDTO> newgpvDTOs=new ArrayList<>();
		List<GoodsproPertiesValueDTO> gpvDTOs=productDTO.getGoodspropertiesvalue();
		for(GoodsproPertiesValueDTO gpvDTO:gpvDTOs) {
			GoodsproPertiesValueDTO newGpDTO=new GoodsproPertiesValueDTO();
			BeanUtils.copyProperties(newGpDTO, gpvDTO);
			cnt++;
			
			if(gpvDTO.isDefaultflag()) {
				defaultUnitFlag=true;
				defaultCnt++;
			}
			
			//没有默认单位自动默认最后一个单位为默认单位
			if(cnt==gpvDTOs.size()&&!defaultUnitFlag) {
				newGpDTO.setDefaultflag(true);				
				cnt=0;
			}
			
			//如果有多个默认单位，去掉多余的默认单位
			if(defaultCnt==2) {
				newGpDTO.setDefaultflag(false);
				defaultCnt=1;
			}
			
			newGpDTO.setOper(unitOper);
			newgpvDTOs.add(newGpDTO);
		}
		
		//重新组装商品信息
		newPDTO.setOper(productOper);
		newPDTO.setGoodsproperties(newGpDTOs);
		newPDTO.setGoodspropertiesvalue(newgpvDTOs);
		
		return newPDTO;
	}
	
	public Product  saveProduct(Product product,ProductDTO productDTO,Long sysCodeId,Long shopId)throws Exception {
		Long productId=0L;
		if(productDTO.getOper()==0) {	//add
			product=new Product();
			BeanUtils.copyProperties(product,productDTO);
			product.setSyscodeid(sysCodeId); 
			product.setShopid(shopId);
			product.setPid(0L);
			product.setCode("");
			product.setItemlabel("");
			product.setMainlyflag(true);
			product.setDisabledflag(false);
			product.setFreighttype(productDTO.getFreightflag());

			productService.save(product);
			productId=product.getId();
			 //详情
			for(GoodsDetailsDTO goodsDetailsDTO: productDTO.getGoodsdetails()) {
				this.saveProductDetails(goodsDetailsDTO, productId, sysCodeId);
			}
			
			//图片
			this.saveProductImg(productDTO, productId, sysCodeId);
					
			 //商品分类关系
			if (StringUtils.isNotEmpty(productDTO.getGoodsclassid())) {
				RelProductCategory relProductCategory= new RelProductCategory();
				relProductCategory.setCategoryid(new Long(productDTO.getGoodsclassid()) );
				relProductCategory.setProductid(productId);
				relProductCategory.setSyscodeid(sysCodeId);
				relProductCategoryService.save(relProductCategory);
				
			}
			
		}else if(productDTO.getOper()==1){	//update
			product=this.updateProduct(productDTO, sysCodeId,shopId);
			productId=product.getId();
		}
		
	   if (productDTO.getGoodsproperties()!=null) {
		 //属性  对应供应链的单位
		for(GoodsPropertiesDTO goodsPropertiesDTO:productDTO.getGoodsproperties()) {
			for(GoodsPropertiesDetailsDTO goodsPropertiesDetailsDTO:goodsPropertiesDTO.getDetails()) {
				if(goodsPropertiesDetailsDTO.getOper()==0) {
					ProductAttrvalue productAttrvalue= new ProductAttrvalue();
					productAttrvalue.setMatchid(goodsPropertiesDetailsDTO.getPertiesid());
					productAttrvalue.setName(goodsPropertiesDetailsDTO.getPertiesname());
					productAttrvalue.setSeqnum(100);
					productAttrvalue.setProductId(product.getId());
					productAttrvalue.setSyscodeid(sysCodeId);
					productAttrvalue.setTypeid(new Long(1));
					
					productAttrvalueService.save(productAttrvalue);
					
				}else if(goodsPropertiesDetailsDTO.getOper()==1) {
					this.updateProductAttrValue(productDTO, sysCodeId, productId);
				}
			}
		}
	   }
		if (productDTO.getGoodspropertiesvalue()!=null) {
			//属性组合方案
			for(GoodsproPertiesValueDTO goodsproPertiesValueDTO:productDTO.getGoodspropertiesvalue()) {
				if(goodsproPertiesValueDTO.getOper()==0) {
					ProductAttrplan productAttrplan=new ProductAttrplan();
					productAttrplan.setProductId(product.getId());
					productAttrplan.setDefaultFlag(goodsproPertiesValueDTO.isDefaultflag());
					if (goodsproPertiesValueDTO.getSalestate()==0) {
						productAttrplan.setDisabledflag( false);
					}else {
						productAttrplan.setDisabledflag( true);
					}
					
					productAttrplan.setInventory(goodsproPertiesValueDTO.getSaleamount());
					productAttrplan.setSyscodeid(sysCodeId); 
					productAttrplan.setWeight(goodsproPertiesValueDTO.getStandardweight());
					productAttrplanService.save(productAttrplan);
					
					ProductPrice productPrice =new ProductPrice();
					productPrice.setAttrplanid(productAttrplan.getId());
					productPrice.setSyscodeid(sysCodeId);
					productPrice.setAllflag(true);
					productPrice.setOneid(0L);
					productPrice.setPrice(goodsproPertiesValueDTO.getDefaultprice());
					productPrice.setProductid(product.getId());
					productPrice.setBegindate(new Date());
					productPrice.setEnddate(new Date());
					productPriceService.save(productPrice);
					
					List<Long> list=	productAttrvalueService.findIdBySPM(sysCodeId, product.getId(), goodsproPertiesValueDTO.getIds());
					for(Long productAttrvalueId:list) {
	
						 ProductAttrplanDetail detail= new ProductAttrplanDetail();
					     detail.setAttrplanid(productAttrplan.getId());
					     detail.setAttrvalueid(productAttrvalueId);
					     detail.setSyscodeid(sysCodeId);
					     productAttrplanDetailService.save(detail);	
					} 
					
				}else if(goodsproPertiesValueDTO.getOper()==1) {
					List<Long> list=productAttrvalueService.findIdBySPM(sysCodeId, productId, goodsproPertiesValueDTO.getIds());
					if(list.size()>0) {
						this.updateProductAttrplan(productDTO, sysCodeId, productId, list.get(0));
					}
				}
			}

		}
		return product;
	}

	/**
	 * 保存商品详情
	 */
	public void saveProductDetails(GoodsDetailsDTO goodsDetailsDTO,Long productId,Long code) throws Exception{
		ProductDetails productDetails=new ProductDetails();
		BeanUtils.copyProperties(productDetails,goodsDetailsDTO);
		productDetails.setProductid(productId);
		productDetails.setSeqnum(100);
		productDetails.setType(1);
		productDetails.setSyscodeid(code);
		productDetailsService.save(productDetails);
	}

	/**
	 * 保存图片
	 */
	public void saveProductImg(ProductDTO productDTO,Long productId,Long code) throws Exception{
		boolean typeFlag=false;
		if(productDTO.getGoodsimg() !=null && productDTO.getGoodsimg().size()>0) {
			for (ImgDTO imgDTO : productDTO.getGoodsimg()) {
				if (imgDTO.getImgtype()==0) {// 0：展示图 1：详情图
					typeFlag=true;
					ProductImg productImg=new ProductImg();
					BeanUtils.copyProperties(productImg, imgDTO);
					productImg.setProductid(productId);
					productImg.setUrl(imgDTO.getImgurl().toString());
					productImg.setSyscodeid(code);
					productImg.setListflag(1); 
					productImgService.save(productImg);
					
				}else {
					ProductDetails productDetails=new ProductDetails();
					BeanUtils.copyProperties(productDetails,imgDTO);
					productDetails.setProductid(productId);
					productDetails.setSeqnum(100);
					productDetails.setType(2);
					productDetails.setName("详情图");
					productDetails.setVal(imgDTO.getImgurl());
					productDetails.setSyscodeid(code);
					productDetailsService.save(productDetails);
				}
				 
			}
			
			//展示图为空，插一条url为空的行
			if(!typeFlag) {
				ProductImg productImg=new ProductImg();
				productImg.setProductid(productId);
				productImg.setUrl("");
				productImg.setSyscodeid(code);
				productImg.setListflag(1); 
				productImgService.save(productImg);
			}
			
		}else {
			ProductImg productImg=new ProductImg();
			productImg.setProductid(productId);
			productImg.setUrl("");
			productImg.setSyscodeid(code);
			productImg.setListflag(1); 
			productImgService.save(productImg);
		}
		
	}
	/**
	 * 更新商品主表
	 */
	public Product updateProduct(ProductDTO pd,Long sysCodeId,Long shopId) throws Exception{

		//根据sysCodeId,shopId和matchId找到对应的商品
		Product product=new Product();
		List<String> list=new ArrayList<>();
		list.add(pd.getMatchid());
		List<Product> productList=productService.findProductBySSM(sysCodeId, shopId, list);
		if(productList!=null&&productList.size()>0) {
			product=productList.get(0);
		}else {
			//TODO需要补充
			throw new Exception();
		}
		
		Long productId=product.getId();
		
		//更新product
		BeanUtils.copyProperties(product, pd);
		product.setHiddenflag(pd.getHiddenflag()==0?false:true);
		product.setModifyDate(new Date());
		product.setShopid(shopId);
		product.setFreighttype(pd.getFreightflag());
		
		productService.update(product);
		
		//更新商品详情
		this.updateProductDetails(pd,sysCodeId, productId);
		
		//更新图片信息
		this.updateProductImg(pd,sysCodeId, productId);
		
		//更新品项属性分类的值
		this.updateProductAttrValue(pd, sysCodeId, productId);
		
		return product;
	}
	
	/**
	 * 更新品项属性分类的值
	 */
	public void updateProductAttrValue(ProductDTO pd,Long sysCodeId,Long productId) {
		List<GoodsPropertiesDetailsDTO> details=new ArrayList<>();
		List<GoodsPropertiesDTO> gpDTOList=pd.getGoodsproperties();
		
		for(GoodsPropertiesDTO gpDTO:gpDTOList) {
			Long id=gpDTO.getId();
			if(id==1L) {
				details=gpDTO.getDetails();
			}
		}
		
		for(GoodsPropertiesDetailsDTO gpdDTO:details) {
			String matchId=gpdDTO.getPertiesid();
			ProductAttrvalue pav=productAttrValueService.findProductAttrvalueBySTMP(sysCodeId, 1, matchId, productId);
			pav.setName(gpdDTO.getPertiesname());
			pav.setModifyDate(new Date());
			
			productAttrValueService.update(pav);
			
			//更新属性组合方案表
			Long attrvalueId=pav.getId();
			this.updateProductAttrplan(pd, sysCodeId, productId, attrvalueId);
			
		}
		
		
	}
	
	/**
	 * 更新属性组合方案表
	 * matchId:
	 */
	public void updateProductAttrplan(ProductDTO pd,Long syscodeId,Long productId,Long attrvalueId) {
		
		Long attrplanId=productAttrplanDetailService.findAttrplanIdByAttrvalueId(attrvalueId);
		//根据attrplanid找到对应的product_attrvalue中的matchId
		String matchIds=productAttrValueService.findMatchIdByAttrplanId(attrplanId);
		
		ProductAttrplan pa=productAttrplanService.findProductAttrplanBySP(attrplanId);
		ProductPrice pp=productPriceService.findProductPriceBySPAO(syscodeId, productId, attrplanId, 0L);
		List<GoodsproPertiesValueDTO> gpvDTOList=pd.getGoodspropertiesvalue();
		for(GoodsproPertiesValueDTO gpvDTO:gpvDTOList) {
			String ids=gpvDTO.getIds();
			if(matchIds.equals(ids)) {			
				pa.setDisabledflag(gpvDTO.getSalestate()==0?false:true);
				pa.setWeight(gpvDTO.getStandardweight());
				if(gpvDTO.getSalestate()==1) {
					//下架商品自动去掉默认单位
					pa.setDefaultFlag(false);
				}else {
					pa.setDefaultFlag(gpvDTO.isDefaultflag());
				}
				pa.setInventory(gpvDTO.getSaleamount());
				pa.setModifyDate(new Date());
				
				productAttrplanService.update(pa);
				
				//更新标准价格
				pp.setPrice(gpvDTO.getDefaultprice());
				pp.setAllflag(true);
				pp.setModifyDate(new Date());
				productPriceService.update(pp);
			}
			
		}
	}
	
	/**
	 * 更新商品详情表
	 */
	public void updateProductDetails(ProductDTO pd,Long syscodeId,Long productId) throws Exception{
		productDetailsService.delProductDetailsBySP(syscodeId, productId);
		for(GoodsDetailsDTO goodsDetailsDTO: pd.getGoodsdetails()) {
			this.saveProductDetails(goodsDetailsDTO, productId, syscodeId);
		}
	}
	
	/**
	 * 更新商品图片表
	 */
	public void updateProductImg(ProductDTO pd,Long syscodeId,Long productId) throws Exception{
		productImgService.delProductImgBySP(syscodeId, productId);
		this.saveProductImg(pd, productId, syscodeId);
		
	
	}

	/**
	 * 更改商品禁用标记
	 */
	public void checkProductDisabledFlag(Long sysCodeId,String productIds) {
		String stopIds="";
		String startIds="";
		productIds=productIds.substring(0, productIds.length()-1);
		String[] idArry=productIds.split(",");
		List<Long> productList=new ArrayList<>();
		
		//得到该次新增或更新的不被禁用的商品
		List<Map<String, Object>> list=productService.getProductIdBySp(sysCodeId, productIds);
		if(list.size()>0&&list.get(0)!=null) {
			for(Map<String, Object> map:list) {
				Long id=Long.valueOf(map.get("id").toString());
				productList.add(id);
			}
		}
		
		if(productList.size()>0) {
			//分别得到需要禁用的商品id和启用的商品id
			for(int i=0;i<idArry.length;i++) {
				if(productList.contains(Long.valueOf(idArry[i]))) {
					startIds+=idArry[i]+",";
				}else {
					stopIds+=idArry[i]+",";
				}
			}
			
			//启用商品
			if(StringUtils.isNotBlank(startIds)) {
				startIds=startIds.substring(0, startIds.length()-1);
				productService.changeProductDisabledFlag(sysCodeId, startIds, true);
			}
			//禁用商品
			if(StringUtils.isNotBlank(stopIds)) {
				stopIds=stopIds.substring(0,stopIds.length()-1);
				productService.changeProductDisabledFlag(sysCodeId, stopIds, false);
			}
			
		}else {
			//全部禁用
			productService.changeProductDisabledFlag(sysCodeId, productIds, false);
		}
			
		
	}

	/**
	 * 判断门店下的商品是否全部隐藏，如果全部隐藏，则门店隐藏，否则门店不隐藏。
	 */
	public void changeShopHiddenFlag(Long sysCodeId,Shop shop) {
		int shopHiddenFlag=1;
		List<Product> proList=productService.findProductBySS(sysCodeId, shop.getId());
		for(Product product:proList) {
			//有一个商品不隐藏，则门店不隐藏
			if(!product.getHiddenflag()) {
				shopHiddenFlag=0;
				break;
			}
		}
		
		if(shopHiddenFlag==0) {
			if(shop.getHiddenflag()) {
				shopService.changeHiddenFlagOfShop(shop.getId(), sysCodeId, shopHiddenFlag);
			}
		}else {
			if(!shop.getHiddenflag()) {
				shopService.changeHiddenFlagOfShop(shop.getId(), sysCodeId, shopHiddenFlag);
			}
		}
		
	}

	/**
	 * 同时还要判断商品是否有且只有一个默认单位，如果没有，则系统将默认设置最先上传的单位为默认单位，
	 * 如果有多个默认单位，系统将更新时间最新的单位设置为默认单位
	 * 因为这种情况不多，所以用逐条更新的方法，sql语句比较简单
	 */
	public void checkProductDefaultUnit(Long sysCodeId,String productIds) {
		List<String> oneDeList=new ArrayList<>();
		List<String> manyDeList=new ArrayList<>();		
		
		productIds=productIds.substring(0,productIds.length()-1);
		List<Map<String, Object>> list=productService.findProductDUCBySP(sysCodeId, productIds);
		if(list!=null&&list.size()>0) {
			
			//整理list，将有一个默认单位的商品id装入oneDeList中，有多个默认单位的装入manyDeList中
			for(Map<String, Object> map:list) {
				int count=Integer.valueOf(map.get("count").toString());
				Long productId=Long.valueOf(map.get("productid").toString());
				
				if(count>1) {
					manyDeList.add(productId.toString());
				}else {
					oneDeList.add(productId.toString());
				}
				
			}
			
			String[] idsArry=productIds.split(",");
			List<String> idsList=Arrays.asList(idsArry);
			
			for(String id:idsList) {
				
				if((!oneDeList.contains(id))&&(!manyDeList.contains(id))) {	//该商品没有默认单位,系统自动默认单位
					productService.changeNoUnitProductDU(sysCodeId, id);
				}
				
				if(manyDeList.contains(id)) {	//该商品有多个默认单位，系统先将默认单位清空，然后系统自动默认
					productService.changeManyUnitProductDU(sysCodeId, id);
				}
				
//				int count=Integer.valueOf(map.get("count").toString());
//				Long productId=Long.valueOf(map.get("productid").toString());
//				if(!idsList.contains(productId.toString())) {		//该商品没有默认单位,系统自动默认单位
//					productService.changeNoUnitProductDU(sysCodeId, productId.toString());
//				} 
//				if(count>1) {	//该商品有多个默认单位，系统先将默认单位清空，然后系统自动默认
//					productService.changeManyUnitProductDU(sysCodeId, productId.toString());
//				}
			}
		}
		else {		//所有商品都没有默认单位
			String proArr[]=productIds.split(",");
			for(int i=0;i<proArr.length;i++) {
				productService.changeNoUnitProductDU(sysCodeId, proArr[i]);
			}
		}
		
	}

	@Override
	public Map<String, Object> matchProductPriceInfo(BaseDTO<List<ProductPriceDataDTO>> baseDTO) throws Exception {
		Long shopId=0L;
		
		Long sysCodeId =baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
		List<ProductPriceDataDTO> productPriceDataDTOs=baseDTO.getData();
		
		for(ProductPriceDataDTO ppdDTO:productPriceDataDTOs) {
			String organMatchId=ppdDTO.getShopid();
			//先找到对应的match_organ 中的id
			Long organId=matchOrganService.getMatchOrganIdBySM(sysCodeId, organMatchId);
			//再找到对应的shopId
			Shop shop=shopService.getShop(sysCodeId, organId);
			shopId=shop.getId();
			
			//保存商品对应不同的客户的价格
			List<ProductPriceDTO> productPriceDTOs=ppdDTO.getDetails();
			this.saveProductPrice(sysCodeId, shopId, productPriceDTOs);
			
		}
		
		return null;
	}

	/**
	 * 保存商品对应不同的客户的价格
	 */
	public void saveProductPrice(Long sysCodeId,Long shopId,List<ProductPriceDTO> productPriceDTOs) throws Exception{
		Long productId=0L;
		Long attrvalueId=0L;
		Long attrplanId=0L;
		
		
		for(ProductPriceDTO ppdDTO:productPriceDTOs) {
			Long cusSysCode=ppdDTO.getCussyscode(); 
			String itemId=ppdDTO.getMatchid();
			List<String> list=new ArrayList<>();
			list.add(itemId);
			
			//根据cussyscode得到对应客户的商城注册号
			Long cusSysCodeId=baseCodeService.checkSysCodeValidity(cusSysCode);
			
			//根据sysCodeId,shopId和matchId找到对应的商品
			Product product=new Product();
			List<Product> productList=productService.findProductBySSM(sysCodeId, shopId, list);
			if(productList!=null&&productList.size()>0) {
				product=productList.get(0);
				productId=product.getId();
				
				//存储商品的价格，先删后插
				List<ProductPricePertiesValueDTO> productPricePertiesValueDTOs=ppdDTO.getGoodspropertiesvalue();
				for(ProductPricePertiesValueDTO pppDTO:productPricePertiesValueDTOs) {
					String ids=pppDTO.getIds();
					BigDecimal productPrice=pppDTO.getProductprice();
					Date beginDate=sdf.parse(pppDTO.getBegindate());
					Date endDate=sdf.parse(pppDTO.getEnddate());
					String unitMatchId=ids.split(",")[0];//因为目前仅支持单位，所以ids里只有单位id
					
					//查找上传客户对应的商品价格，有则更新，没有则新增
					ProductAttrvalue pav=productAttrValueService.findProductAttrvalueBySTMP(sysCodeId, 1, unitMatchId, productId);
					attrvalueId=pav.getId();
					if(attrvalueId!=null&&attrvalueId!=0) {
						attrplanId=productAttrplanDetailService.findAttrplanIdByAttrvalueId(attrvalueId);
						//删除原有数据，然后新增
						productPriceService.delProductPriceBySPAO(sysCodeId, productId, attrplanId, cusSysCodeId);
						ProductPrice pp=new ProductPrice();
						pp.setAllflag(false);
						pp.setAttrplanid(attrplanId);
						pp.setOneid(cusSysCodeId);
						pp.setProductid(productId);
						pp.setSyscodeid(sysCodeId);
						pp.setBegindate(beginDate);
						pp.setEnddate(endDate);
						pp.setPrice(productPrice);
						productPriceService.save(pp);
						
					}else {
						//说明传过来的商品属性不存在
						break;
					}		
				}
				
			}else {
				//TODO需要补充
				break;
			}
		}
		
	}

	@Override
	public Map<String, Object> matchProductCustomerInfo(BaseDTO<List<ProductCustomerDataDTO>> baseDTO)
			throws Exception {
		Long shopId=0L;
		
		Long sysCodeId =baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
		List<ProductCustomerDataDTO> productCustomerDataDTOs=baseDTO.getData();
		
		for(ProductCustomerDataDTO pcdDTO:productCustomerDataDTOs) {
			String organMatchId=pcdDTO.getShopid();
			//先找到对应的match_organ 中的id
			Long organId=matchOrganService.getMatchOrganIdBySM(sysCodeId, organMatchId);
			//再找到对应的shopId
			Shop shop=shopService.getShop(sysCodeId, organId);
			shopId=shop.getId();
			
			//先删除商品与客户的的对应关系
			productService.delProductCustomerRelation(sysCodeId);
			
			//保存商品与客户的对应关系
			List<ProductCustomerDetailsDTO> productCustomerDetailsDTOs=pcdDTO.getDetails();
			this.saveProductCustomer(sysCodeId, shopId, productCustomerDetailsDTOs);
			
		}
		
		return null;
	}
	
	/**
	 * 保存商品与客户的对应关系
	 */
	public void saveProductCustomer(Long sysCodeId,Long shopId,List<ProductCustomerDetailsDTO> productCustomerDetailsDTOs) {
		
		for(ProductCustomerDetailsDTO pcdDTO:productCustomerDetailsDTOs) {
			String matchId="";
			List<String> list=new ArrayList<>();
			
			//根据传过来的客户商城注册号得到对应的注册号id
			Long cusSysCode=pcdDTO.getCussyscode();
			Long cusSysCodeId =baseCodeService.checkSysCodeValidity(cusSysCode);
			
			//传过来的客户注册号商城不存在，不存
			if(cusSysCodeId==0||cusSysCodeId==null) {
				continue;
			}else {
				List<ProductCustomerGoodsDTO> productCustomerGoodsDTOs=pcdDTO.getDetails();
				for(ProductCustomerGoodsDTO pcgDTO:productCustomerGoodsDTOs) {
					matchId+="'"+pcgDTO.getMatchid()+"',";
					list.add(pcgDTO.getMatchid());
				}
				
				//根据sysCodeId、shopId和matchid得到商品信息
				matchId=matchId.substring(0,matchId.length()-1);
				List<Product> proList=productService.findProductBySSM(sysCodeId, shopId, list);
				if(proList.size()>0&&proList.get(0)!=null) {
					for(Product pro:proList) {
						RelProductCode rpc=new RelProductCode();
						rpc.setProductid(pro.getId());
						rpc.setSyscodeid(cusSysCodeId);
						rpc.setSellsyscodeid(sysCodeId);
						rpc.setSellshopid(shopId);
						
						relProductCodeService.save(rpc);
					}
				}
				
			}
			
		}
		
//		return insertValues.toString();
		
	}
	
}
